<template>
  <el-container class="app-container app-containerMoneytabel">
    <el-aside class="aside-box">
      <detp-tree :dept="dept" ref="deptTree"></detp-tree>
    </el-aside>
    <el-main class="main-box">
      <div class="filter-container">
        <el-input size="small" @keyup.enter.native="handleFilter" placeholder="请输入用户名称" class="filter-item smallSelect"
          v-model="listQuery.nickName"></el-input>
        <el-input size="small" @keyup.enter.native="handleFilter" placeholder="请输入角色名称" style="marginLeft: 15px;"
          class="filter-item smallSelect" v-model="listQuery.roleName"></el-input>
        <el-input size="small" @keyup.enter.native="handleFilter" placeholder="请输入部门名称" style="marginLeft: 15px;"
          class="filter-item smallSelect" v-model="listQuery.deptName"></el-input>
        <el-button size="small" class="filter-item filter-itemBut" style="marginLeft: 10px;" type="primary" icon="el-icon-search"
          @click="handleFilter">搜索</el-button>
        <el-button size="small" class="filter-item filter-itemBut" style="margin-left: 10px;" @click="handleCreate"
          type="primary" icon="el-icon-edit">添加</el-button>
      </div>
      <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit
        highlight-current-row>
        <el-table-column type="index" width="50" label="序号"></el-table-column>
        <el-table-column align="center" label='账号'>
          <template slot-scope="scope">
            {{scope.row.username}}
          </template>
        </el-table-column>
        <el-table-column label="用户名称" align="center">
          <template slot-scope="scope">
            {{scope.row.nickName}}
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center">
          <template slot-scope="scope">
            {{scope.row.phone}}
          </template>
        </el-table-column>
        <el-table-column label="座机" align="center">
          <template slot-scope="scope">
            {{scope.row.officePhone}}
          </template>
        </el-table-column>
        <el-table-column label="所属部门" align="center">
          <template slot-scope="scope">
            {{scope.row.deptName}}
          </template>
        </el-table-column>
        <el-table-column label="角色" align="center">
          <template slot-scope="scope">
            {{scope.row.zhStr}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            {{enabledMap[scope.row.enabled]}}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template slot-scope="scope">
            {{scope.row.remark}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="150" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">禁用</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page"
          :page-sizes="[10,20,30, 50]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-main>
    <!--新增修改弹出层-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form size="small" :rules="rules" ref="dataForm" :model="temp"  label-width="80px" >
        <el-input v-model="temp.id" v-show="false"></el-input>
        <el-form-item label="账号" prop="username" v-if="dialogStatus=='create'">
          <el-input v-model="temp.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogStatus=='create'">
          <el-input type="password" v-model="temp.password"></el-input>
        </el-form-item>
        <el-form-item label="头像">
          <el-upload
            class="avatar-uploader"
            :action="uploadURL"
            :show-file-list="false"
            name="file"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="名称" prop="nickName">
          <el-input v-model="temp.nickName"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="temp.phone"></el-input>
        </el-form-item>
        <el-form-item label="座机" prop="officePhone">
          <el-input v-model="temp.officePhone"></el-input>
        </el-form-item>
        <el-form-item label="地区" prop="areaCode" class="dialog-areaCode_User">
          <region-selector :disabled="true" :province="region.province" :city="region.city" :area="region.area" 
            :street="region.street" :community="region.community"
             @region="setAreaCode" ref="regionSelector"></region-selector>
             <el-input style="display:none" type="hidden" v-model="temp.areaCode"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="temp.remark"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="enabled">
          <el-radio-group v-model="temp.enabled">
            <el-radio :label=true>启用</el-radio>
            <el-radio :label=false>禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          {{temp.deptName}}
          <br>
          <el-button @click="openDeptTree">选择机构部门</el-button>
        </el-form-item>
        <el-form-item label="角色" prop="roleNames" class="dialog-roleNames_User">
          <role-checkbox class="user-roleNames-role-checkbox" :role-names="temp.roleNames" ref="roleCheckbox"></role-checkbox>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">提交</el-button>
        <el-button v-else type="primary" @click="updateData">更新</el-button>
      </div>
      <el-dialog width="40%" title="选择机构部门" :visible.sync="detpVisible" append-to-body>
        <detp-tree v-if="temp.deptId" :checked-keys="[temp.deptId]" :temp="temp"  ref="updateDeptTree"></detp-tree>
        <detp-tree v-else :temp="temp"  ref="updateDeptTree"></detp-tree>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="detpVisible = false">确定</el-button>
        </div>
      </el-dialog>
    </el-dialog>
  </el-container>
</template>
<script>
import { queryPage, create, update, deleteById } from "@/api/user";
import { queryInfo } from "@/api/dept";
import { packRegionCode } from "@/utils/region";
import DetpTree from "../components/DetpTree";
import RoleCheckbox from "../components/RoleCheckbox";
import RegionSelector from "@/components/RegionSelector";
import md5 from "js-md5";
import {
  validateMobilePhone,
  validateAccount,
  validatePassword
} from "@/utils/validate";

export default {
  components: {
    DetpTree,
    RoleCheckbox,
    RegionSelector
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!validateAccount(value)) {
        callback(new Error("请输入正确的用户名"));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      if (!validateMobilePhone(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    const validatePass = (rule, value, callback) => {
      if (!validatePassword(value)) {
        callback(new Error("密码必须由6-20个数字与字母组成"));
      } else {
        callback();
      }
    };
    return {
      uploadURL: process.env.BASE_API + "/file/upload",
      downloadURL: process.env.BASE_API + "/file/",
      list: null,
      total: 0,
      listLoading: true,
      imageUrl: "",
      listQuery: {
        page: 1,
        size: 10,
        orgId: null,
        roleName: null,
        deptName: null,
        nickName: null
      },
      dialogFormVisible: false,
      detpVisible: false,
      dialogStatus: "",
      textMap: {
        update: "更新",
        create: "添加"
      },
      dept: {
        id: null,
        name: null
      },
      selectedDept: false,
      enabledMap: {
        true: "启用",
        false: "禁用"
      },
      temp: {
        id: null,
        username: null,
        password: null,
        nickName: null,
        avatar: null,
        phone: null,
        officePhone: null,
        areaCode: null,
        remark: null,
        deptId: null,
        enabled: true,
        roleNames: []
      },
      region: {
        province: 0,
        city: 0,
        area: 0,
        street: 0,
        community: 0
      },
      rules: {
        username: [
          {
            required: true,
            message: "请输入账号",
            trigger: "blur",
            validator: validateUsername
          }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { validator: validatePass }
        ],
        nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        phone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePhone }
        ],
        areaCode: [{ required: true, message: "请选择地区", trigger: "blur" }],
        deptId: [
          { required: true, message: "请选择右侧部门", trigger: "change" }
        ]
      }
    };
  },
  mounted: function() {
    this.fetchData();
  },
  watch: {
    dept: {
      handler() {
        this.listQuery.orgId = this.dept.id;
        this.fetchData();
        this.setDeptRegion();
        this.selectedDept = true;
        this.temp.deptName = this.dept.name;
      },
      deep: true
    }
  },
  methods: {
    fetchData() {
      this.listLoading = true;
      queryPage(this.listQuery).then(response => {
        this.list = response.data.records;
        this.total = response.data.total;
        this.listLoading = false;
      });
      this.listLoading = false;
    },
    setDeptRegion() {
      //查找部门详情
      queryInfo(this.dept.id).then(res => {
        //地区处理
        let areaCode = res.data.areaCode;
        if (areaCode && areaCode.length > 5) {
          this.region = packRegionCode(areaCode);
        }
        this.temp.areaCode = areaCode;
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.fetchData();
    },
    handleSizeChange(val) {
      this.listQuery.size = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.fetchData();
    },
    handleCreate() {
      if(!this.dept.id){
        this.$message.error('请先选择右侧机构部门')
        return
      }
      this.resetTemp();
      this.imageUrl = null
      if (this.dept.id) {
        this.temp.deptId = this.dept.id;
      } else {
        this.temp.deptId = null;
        this.temp.deptName = null;
      }
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.roleCheckbox.init();
        this.$refs["dataForm"].clearValidate();
        this.$refs.deptTree.$refs.tree.setCheckedKeys([]);
      });
    },
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          this.temp.password = md5(this.temp.password);
          create(this.temp).then(() => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "创建成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.imageUrl = null;
      //地区处理
      if (this.temp.areaCode && this.temp.areaCode.length > 5) {
        this.region = packRegionCode(this.temp.areaCode);
      }
      if (this.temp.avatar) {
        this.imageUrl = this.downloadURL + this.temp.avatar;
      }
      if (!this.temp.roleNames) {
        this.temp.roleNames = [];
      }
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs.roleCheckbox.init();
        this.$refs["dataForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.temp);
          update(tempData).then(() => {
            this.fetchData();
            this.dialogFormVisible = false;
            this.$notify({
              title: "成功",
              message: "更新成功",
              type: "success",
              duration: 2000
            });
          });
        }
      });
    },
    handleDelete(row) {
      const loading = this.$loading({
        lock: true,
        text: "提交中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      setTimeout(() => {
        loading.close();
      }, 800);
      this.$confirm("删除后不可恢复, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          deleteById(row.username).then(() => {
            this.$notify({
              title: "成功",
              message: "删除成功",
              type: "success",
              duration: 2000
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    setAreaCode(value) {
      if (value.code) {
        this.temp.areaCode = value.code;
      }
    },
    openDeptTree() {
      this.detpVisible = true;
      let temp = this;
      setTimeout(() => {
        temp.$refs.updateDeptTree.updateChecked([temp.temp.deptId]);
      }, 100);
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.temp.avatar = res.data.fileId;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    resetTemp() {
      this.temp = {
        id: null,
        username: null,
        password: null,
        avatar: null,
        nickName: null,
        areaCode: this.temp.areaCode,
        phone: null,
        officePhone: null,
        remark: null,
        detpId: this.temp.deptId,
        deptName: this.temp.deptName,
        enabled: true,
        roleNames: []
      };
    },
    resetRegion() {
      this.region = {
        province: 0,
        city: 0,
        area: 0,
        street: 0,
        community: 0
      };
    }
  }
};
</script>

<style scoped>
.dialog-roleNames_User .user-roleNames-role-checkbox {
  display: flex;
  flex-wrap: wrap;
}
.main-box {
  padding: 0;
  width: calc(100% - 320px);
  margin-left: 20px;
}

.app-container {
  overflow: hidden;
}

.user-roleNames-role-checkbox .el-checkbox {
  margin-right: 15px !important;
  margin-top: 10px !important;
  overflow: hidden;
}

.filter-container {
  margin-bottom: 20px;
  overflow: hidden;
}

.pagination-container {
  margin-top: 25px;
  overflow: hidden;
  display: flex;
  justify-content: flex-end;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.dialog-areaCode_User {
  min-height: 50px;
}
</style>